#include <Windows.h>
#include <MsHTML.h>
#include <atlbase.h>
#include <oleacc.h>
#include <tchar.h>
#include <gdiplus.h>
#pragma comment (lib,"Gdiplus.lib")

#include <memory>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <unordered_map>
#include <functional>
#include <algorithm>

#include "Activity.h"
#pragma comment (lib,"bot.lib")

using namespace std;
using namespace Gdiplus;

CComQIPtr<IHTMLDocument2> GetDocInterface(HWND hWnd) ;

int main()
{
	CoInitialize( NULL );


	//cout << "wait for debugging..." << endl;
	//getchar();

	//		
	try
	{
		CComQIPtr<IHTMLDocument2> spDoc = GetDocInterface(FindWindowW(L"IEFrame", NULL));
		

		CActivity::Current()->Run(spDoc);

		cout << "Done!" << endl;
	}
	catch(const wstring& s)
	{
		wcout << s << endl;
	}
	catch(...)
	{
		cout << "Unknown exception" << endl;
	}
	//
	CoUninitialize();
	return 0;
}




BOOL CALLBACK EnumChildProc(HWND hwnd,LPARAM lParam)
{
	TCHAR	buf[100];

	::GetClassName( hwnd, (LPTSTR)&buf, 100 );
	if ( _tcscmp( buf, _T("Internet Explorer_Server") ) == 0 )
	{
		*(HWND*)lParam = hwnd;
		return FALSE;
	}
	else
		return TRUE;
};

//You can store the interface pointer in a member variable 
//for easier access
CComQIPtr<IHTMLDocument2> GetDocInterface(HWND hWnd) 
{
	CComQIPtr<IHTMLDocument2> spDoc;
	//unique_ptr<CComQIPtr<IHTMLDocument2>> upspDoc(pspDoc);

	// Explicitly load MSAA so we know if it's installed
	HINSTANCE hInst = ::LoadLibrary( _T("OLEACC.DLL") );
	if ( hInst != NULL )
	{
		if ( hWnd != NULL )
		{
			HWND hWndChild=NULL;
			// Get 1st document window
			::EnumChildWindows( hWnd, EnumChildProc, (LPARAM)&hWndChild );
			if ( hWndChild )
			{				
				LRESULT lRes;

				UINT nMsg = ::RegisterWindowMessageW(L"WM_HTML_GETOBJECT");
				::SendMessageTimeoutW( hWndChild, nMsg, 0L, 0L, SMTO_ABORTIFHUNG, 1000, (DWORD*)&lRes );

				LPFNOBJECTFROMLRESULT pfObjectFromLresult = (LPFNOBJECTFROMLRESULT)::GetProcAddress( hInst, "ObjectFromLresult" );
				if ( pfObjectFromLresult != NULL )
				{
					HRESULT hr;
					hr = (*pfObjectFromLresult)( lRes, IID_IHTMLDocument2, 0, (void**)&spDoc );
					if ( SUCCEEDED(hr) )
					{
						//upspDoc.reset(pspDoc);

						// Change background color to red
						spDoc->put_title( CComBSTR(L"Chinese people are great!") );
						//CComBSTR szTitle;
						//BSTR szTitle;
						//spDoc->get_title(&szTitle);
						//MessageBoxW(hWnd, szTitle, L"", MB_OK);
						//SysFreeString(szTitle);
						//return spDoc;
					}
				}
			} // else document not ready
		} // else Internet Explorer is not running
		::FreeLibrary( hInst );
	} // else Active Accessibility is not installed

	//unique_ptr<CComQIPtr<IHTMLDocument2>> upspDoc;
	return spDoc;
}

